package com.caojm.mptools.commands;

import com.caojm.mptools.PermissionManager;
import com.caojm.mptools.utils.LoggerUtil;
import com.mojang.brigadier.arguments.StringArgumentType;
import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback;
import net.minecraft.server.command.CommandManager;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.text.Text;


public class GrantCommand {

    private static final PermissionManager permissionManager = new PermissionManager();

    public static void register() {
    CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) ->
        dispatcher.register(
            CommandManager.literal("mp")
                .then(CommandManager.literal("grant")
                    .then(CommandManager.argument("player", StringArgumentType.string())
                        .then(CommandManager.argument("permission", StringArgumentType.string())
                            .executes(context -> {
                                String playerName = StringArgumentType.getString(context, "player");
                                String permissionNode = StringArgumentType.getString(context, "permission");

                                // 获取执行命令的玩家名称
                                ServerCommandSource source = context.getSource();
                                String executor = source.getName();

                                // 检查是否为管理员（只有管理员能授予权限）
                                if (!permissionManager.hasPermission(executor, "mingpixeltools.admin")) {
                                source.sendError(Text.literal("你没有权限执行此操作！"));
                                LoggerUtil.logWarning("Player " + executor + " attempted to use /mp grant without proper permission.");
                                return 0;
                                }

                                // 授予玩家权限
                                permissionManager.grantPermission(playerName, permissionNode);
                                source.sendFeedback(() -> Text.of("已成功授予 " + playerName + " 权限: " + permissionNode), false);
                                LoggerUtil.logInfo("Player " + executor + " granted permission " + permissionNode + " to player " + playerName);
                                return 1;  // 返回成功
                            })
                        )
                    )
                )
        )
    );
    }
}
